<template>
	<image v-if="isError"
		src="@/static/img/svg/imgerror.svg"
		lazy-load
		:style="style"
		:class="{reverse: isReverse && isSenderThemselve}"
		@load="onLoad" />
	<image v-else
		class="chat-message-image"
		:style="style"
		:class="{reverse: isReverse && isSenderThemselve}"
		:src="thumbUrl"
		lazy-load
		@tap="preview"
		@load="onLoad"
		@error="onError" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { messageProps, useMessage } from '@/hooks/useMessage'
import XBCCS from 'xbccs'

const emit = defineEmits(['load'])
const isError = ref(false)
const size = reactive({ width: 0, height: 0 })
const props = defineProps(messageProps)
const { isSenderThemselve, messageContent } = useMessage(props)
const thumbUrl = computed(() => {
	let url = messageContent.value.data?.thumbUrl
	url = url.substr(0, 8) == '/upload/' ? XBCCS.getHttpBaseUrl() + url : url
	return url.replace('//upload', '/upload')
})
const fullUrl = computed(() => {
	let url = messageContent.value.data?.url
	url = url.substr(0, 8) == '/upload/' ? XBCCS.getHttpBaseUrl() + url : url
	return url.replace('//upload', '/upload')
})
const style = computed(() => {
	const { width, height, thumbWidth, thumbHeight } = messageContent.value?.data
	if ((!thumbWidth || !thumbHeight) && (!width || !height)) {
		uni.getImageInfo({
			src: thumbUrl.value,
			success: ({ width: imgWidth, height: imgHeight }) => {
				size.width = imgWidth
				size.height = imgHeight
			}
		})
	} else {
		size.width = thumbWidth || width
		size.height = thumbHeight || height
	}

	return XBCCS.util.getImageSize(size.width, size.height, 200)
})

function onLoad(){
	emit('load')
}

function onError(){
	isError.value = true
}

function preview() {
	uni.previewImage({
		urls: [fullUrl.value]
	})
}
</script>

<style lang="scss" scoped>
.chat-message-image {
	border-radius: 0 10rpx 10rpx 10rpx;

	&.reverse {
		border-radius: 10rpx 0 10rpx 10rpx;
	}
}
</style>